package com.qianniu.napi.admin.web;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.google.common.base.Strings;
import com.qianniu.napi.admin.entity.Fenxiao;
import com.qianniu.napi.admin.entity.FenxiaoFan;
import com.qianniu.napi.admin.entity.Jinfo;
import com.qianniu.napi.admin.service.IFenxiaoFanService;
import com.qianniu.napi.admin.service.IFenxiaoService;
import com.qianniu.napi.common.util.ObjectUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.util.*;

/**
 * <p>
 * <p>
 * </p>
 *
 * @author chenxuebin
 * @since 2019-01-16
 */
@Controller
public class FenxiaoFanController {

    private static final Logger logger = LoggerFactory.getLogger(FenxiaoFanController.class);

    @Autowired
    private IFenxiaoFanService fenxiaofanService;
    @Autowired
    private IFenxiaoService fenxiaoService;

    @RequestMapping("admin/fenxiaofan/index")
    public String index(Model model) {

        Fenxiao fenxiao = fenxiaoService.selectOne(new EntityWrapper<Fenxiao>()
                .eq("mpid", ObjectUtil.getMpid()));
        if (fenxiao == null) {
            model.addAttribute("msg", "清先设置分销会员级别，再设置分销返佣");
            model.addAttribute("leftlevel", -1);
            model.addAttribute("fxlevel", 0);
            model.addAttribute("jiandian", fenxiao.getJiandian());
            return "admin/fenxiaofan";
        }

        List<Fenxiao> fxlist = fenxiaoService.selectList(new EntityWrapper<Fenxiao>().eq("mpid", ObjectUtil.getMpid()));
        if (fxlist != null) {
            model.addAttribute("hytypes", initHytypes(fxlist));
        } else {
            model.addAttribute("hytypes", initHytypes(new ArrayList<Fenxiao>()));
        }
        Map<String, String> map = new HashMap<String, String>();
        List<FenxiaoFan> listfan = fenxiaofanService.selectList(new EntityWrapper<FenxiaoFan>().eq("mpid", ObjectUtil.getMpid()));

        int fancout = 0;
        int leftlevel = 0;
        if (listfan != null && listfan.size() > 0) {
            for (FenxiaoFan item : listfan) {
                map.put("mlevel" + item.getMlevel().toString(), "1");
            }
            fancout = listfan.size();
        }


        model.addAttribute("fxlevel", fenxiao.getFxlevel());

        JSONArray ja = new JSONArray();
        JSONArray mja = new JSONArray();
        JSONObject jo = null;

        for (int i = 1; i <= fenxiao.getFxlevel(); i++) {
            if (i == 1) map.put("fxlevel_" + i, fenxiao.getFxname1());
            else if(i == 2)map.put("fxlevel_" + i, fenxiao.getFxname2());
            else if(i == 3)map.put("fxlevel_" + i, fenxiao.getFxname3());
            else if(i == 4)map.put("fxlevel_" + i, fenxiao.getFxname4());
            else if(i == 5)map.put("fxlevel_" + i, fenxiao.getFxname5());
            else if(i == 6)map.put("fxlevel_" + i, fenxiao.getFxname6());
            else if(i == 7)map.put("fxlevel_" + i, fenxiao.getFxname7());

//            if (map.containsKey("mlevel" + i)) continue;

            if (i == 1) {
                jo = new JSONObject();
                jo.put("name", fenxiao.getFxname1());
                jo.put("huifei", fenxiao.getHuifei1());
                jo.put("fxlevel", 1);
                if (!map.containsKey("mlevel" + i)) ja.add(jo);
                mja.add(jo);
            } else if (i == 2) {
                jo = new JSONObject();
                jo.put("name", fenxiao.getFxname2());
                jo.put("huifei", fenxiao.getHuifei2());
                jo.put("fxlevel", 2);
                if (!map.containsKey("mlevel" + i)) ja.add(jo);
                mja.add(jo);
            } else if (i == 3) {
                jo = new JSONObject();
                jo.put("name", fenxiao.getFxname3());
                jo.put("huifei", fenxiao.getHuifei3());
                jo.put("fxlevel", 3);
                ja.add(jo);
                mja.add(jo);
            } else if (i == 4) {
                jo = new JSONObject();
                jo.put("name", fenxiao.getFxname4());
                jo.put("huifei", fenxiao.getHuifei4());
                jo.put("fxlevel", 4);
                if (!map.containsKey("mlevel" + i)) ja.add(jo);
                mja.add(jo);
            } else if (i == 5) {
                jo = new JSONObject();
                jo.put("name", fenxiao.getFxname5());
                jo.put("huifei", fenxiao.getHuifei5());
                jo.put("fxlevel", 5);
                if (!map.containsKey("mlevel" + i)) ja.add(jo);
                mja.add(jo);
            } else if (i == 6) {
                jo = new JSONObject();
                jo.put("name", fenxiao.getFxname6());
                jo.put("huifei", fenxiao.getHuifei6());
                jo.put("fxlevel", 6);
                if (!map.containsKey("mlevel" + i)) ja.add(jo);
                mja.add(jo);
            } else if (i == 7) {
                jo = new JSONObject();
                jo.put("name", fenxiao.getFxname7());
                jo.put("huifei", fenxiao.getHuifei7());
                jo.put("fxlevel", 7);
                if (!map.containsKey("mlevel" + i)) ja.add(jo);
                mja.add(jo);
            }
        }

        leftlevel = fenxiao.getFxlevel() - fancout;
        model.addAttribute("fxlist", ja);
        model.addAttribute("mfxlist", mja);
        model.addAttribute("leftlevel", leftlevel);

        return "admin/fenxiaofan";
    }

    @RequestMapping("/admin/fenxiaofan/list")
    @ResponseBody
    public Page<FenxiaoFan> list(@RequestParam(value = "offset", required = false) Integer offset,
                                 @RequestParam(value = "status", required = false) Integer status,
                                 @RequestParam(value = "search", required = false) String search,
                                 @RequestParam(value = "limit", required = false) Integer limit) {
        Wrapper<FenxiaoFan> wrapper = new EntityWrapper<FenxiaoFan>();
        wrapper.eq("mid", ObjectUtil.getMid());
//        if (!Strings.isNullOrEmpty(search))
//            wrapper.like("order_no", search).or().like("remark", search);

        wrapper.orderBy("id", false);
        Page<FenxiaoFan> page = fenxiaofanService.selectPage(new Page<FenxiaoFan>(offset / limit + 1, limit), wrapper);
        return page;
    }

    @RequestMapping("/admin/fenxiaofan/add")
    public String add(@Valid FenxiaoFan bean, BindingResult bindingResult, Model model) {
        // 字段校验
        if (bindingResult.hasErrors()) {
            logger.debug("There are errors! {}", bindingResult);
            return null;
        }
        bean.setCreatetime(new Date());
        bean.setUid(ObjectUtil.getUid());
        bean.setMid(ObjectUtil.getMid());
        bean.setMpid(ObjectUtil.getMpid());


        Fenxiao fenxiao = fenxiaoService.selectOne(new EntityWrapper<Fenxiao>()
                .eq("mpid", ObjectUtil.getMpid()));
        if (fenxiao == null) {
            model.addAttribute("msg", "清先设置分销会员级别，再设置分销返佣");
            model.addAttribute("leftlevel", -1);
            model.addAttribute("fxlevel", 0);
            return "admin/fenxiaofan";
        }

        Map<String, String> map = new HashMap<String, String>();
        List<FenxiaoFan> listfan = fenxiaofanService.selectList(new EntityWrapper<FenxiaoFan>().eq("mpid", ObjectUtil.getMpid()));

        int fancout = 0;
        int leftlevel = 0;
        if (listfan != null && listfan.size() > 0) {
            for (FenxiaoFan item : listfan) {
                map.put("mlevel" + item.getMlevel().toString(), "1");
            }
            fancout = listfan.size();
        }


        model.addAttribute("fxlevel", fenxiao.getFxlevel());

        JSONArray ja = new JSONArray();
        JSONArray mja = new JSONArray();
        JSONObject jo = null;

        for (int i = 1; i <= fenxiao.getFxlevel(); i++) {
            if (i == 1) map.put("fxlevel_" + i, fenxiao.getFxname1());
            else if(i == 2)map.put("fxlevel_" + i, fenxiao.getFxname2());
            else if(i == 3)map.put("fxlevel_" + i, fenxiao.getFxname3());
            else if(i == 4)map.put("fxlevel_" + i, fenxiao.getFxname4());
            else if(i == 5)map.put("fxlevel_" + i, fenxiao.getFxname5());
            else if(i == 6)map.put("fxlevel_" + i, fenxiao.getFxname6());
            else if(i == 7)map.put("fxlevel_" + i, fenxiao.getFxname7());

//            if (map.containsKey("mlevel" + i)) continue;

            if (i == 1) {
                jo = new JSONObject();
                jo.put("name", fenxiao.getFxname1());
                jo.put("huifei", fenxiao.getHuifei1());
                jo.put("fxlevel", 1);
                if (!map.containsKey("mlevel" + i)) ja.add(jo);
                mja.add(jo);
            } else if (i == 2) {
                jo = new JSONObject();
                jo.put("name", fenxiao.getFxname2());
                jo.put("huifei", fenxiao.getHuifei2());
                jo.put("fxlevel", 2);
                if (!map.containsKey("mlevel" + i)) ja.add(jo);
                mja.add(jo);
            } else if (i == 3) {
                jo = new JSONObject();
                jo.put("name", fenxiao.getFxname3());
                jo.put("huifei", fenxiao.getHuifei3());
                jo.put("fxlevel", 3);
                ja.add(jo);
                mja.add(jo);
            } else if (i == 4) {
                jo = new JSONObject();
                jo.put("name", fenxiao.getFxname4());
                jo.put("huifei", fenxiao.getHuifei4());
                jo.put("fxlevel", 4);
                if (!map.containsKey("mlevel" + i)) ja.add(jo);
                mja.add(jo);
            } else if (i == 5) {
                jo = new JSONObject();
                jo.put("name", fenxiao.getFxname5());
                jo.put("huifei", fenxiao.getHuifei5());
                jo.put("fxlevel", 5);
                if (!map.containsKey("mlevel" + i)) ja.add(jo);
                mja.add(jo);
            } else if (i == 6) {
                jo = new JSONObject();
                jo.put("name", fenxiao.getFxname6());
                jo.put("huifei", fenxiao.getHuifei6());
                jo.put("fxlevel", 6);
                if (!map.containsKey("mlevel" + i)) ja.add(jo);
                mja.add(jo);
            } else if (i == 7) {
                jo = new JSONObject();
                jo.put("name", fenxiao.getFxname7());
                jo.put("huifei", fenxiao.getHuifei7());
                jo.put("fxlevel", 7);
                if (!map.containsKey("mlevel" + i)) ja.add(jo);
                mja.add(jo);
            }
        }
//        bean.setMname(map.get("fxlevel_"+bean.getMlevel().toString()));
        bean.insert();

        leftlevel = fenxiao.getFxlevel() - fancout;
        model.addAttribute("fxlist", ja);
        model.addAttribute("mfxlist", mja);
        model.addAttribute("leftlevel", leftlevel);

        return "redirect:index";
    }

    @RequestMapping("/admin/fenxiaofan/getFenxiaoFanById")
    @ResponseBody
    public FenxiaoFan getFenxiaoFanById(long id) {
        FenxiaoFan fenxiaofan = fenxiaofanService.selectById(id);
        return fenxiaofan;
    }

    @RequestMapping("/admin/fenxiaofan/deleteOne")
    @ResponseBody
    public int deleteOne(long id) {
        boolean isSucc = fenxiaofanService.deleteById(id);
        return isSucc ? 1 : 0;
    }

    @RequestMapping("/admin/fenxiaofan/changeState")
    @ResponseBody
    public String changeState(long id, int state) {
        FenxiaoFan bean = new FenxiaoFan();
        bean.setId(id);
        bean.setState(state);
        bean.setModifytime(new Date());
        bean.setModifier(ObjectUtil.getUid());
        fenxiaofanService.updateById(bean);
        return "success";
    }

    @RequestMapping("/admin/fenxiaofan/modify")
    public String update(FenxiaoFan bean) {
        bean.setModifytime(new Date());
        bean.setModifier(ObjectUtil.getUid());
        boolean isSuccc = fenxiaofanService.updateById(bean);
        if (isSuccc) {
            return "redirect:index";
        }
        return "error";
    }

    @RequestMapping("/admin/fenxiaofan/getLeftLevel")
    @ResponseBody
    public Jinfo getLeftLevel(String hytype) {
        Jinfo jinfo = new Jinfo();
        Long mpid = ObjectUtil.getMpid();
        Fenxiao fenxiao = fenxiaoService.selectOne(new EntityWrapper<Fenxiao>()
                .eq("mpid",mpid).eq("hytype",hytype)
        );
        if(fenxiao==null) return jinfo;

        List<FenxiaoFan> fxflist = fenxiaofanService.selectList(new EntityWrapper<FenxiaoFan>()
                .eq("mpid",mpid).eq("hytype",hytype)
        );
        Map<String,String> map = new HashMap();
        // 不加限制
//        for(FenxiaoFan item:fxflist){
//            map.put(item.getMlevel().toString(),item.getHytype().toString());
//        }
        List<Jinfo> list = new ArrayList<>();
        if(!map.containsKey("1")&& !Strings.isNullOrEmpty(fenxiao.getFxname1())){
            Jinfo item = new Jinfo();
            item.setMsg(fenxiao.getFxname1());
            item.setCode(1);
            list.add(item);
        }
        if(!map.containsKey("2")&& !Strings.isNullOrEmpty(fenxiao.getFxname2())){
            Jinfo item = new Jinfo();
            item.setMsg(fenxiao.getFxname2());
            item.setCode(2);
            list.add(item);
        }
        if(!map.containsKey("3")&& !Strings.isNullOrEmpty(fenxiao.getFxname3())){
            Jinfo item = new Jinfo();
            item.setMsg(fenxiao.getFxname3());
            item.setCode(3);
            list.add(item);
        }
        if(!map.containsKey("4")&& !Strings.isNullOrEmpty(fenxiao.getFxname4())){
            Jinfo item = new Jinfo();
            item.setMsg(fenxiao.getFxname4());
            item.setCode(4);
            list.add(item);
        }
        if(!map.containsKey("5")&& !Strings.isNullOrEmpty(fenxiao.getFxname5())){
            Jinfo item = new Jinfo();
            item.setMsg(fenxiao.getFxname5());
            item.setCode(5);
            list.add(item);
        }
        if(!map.containsKey("6")&& !Strings.isNullOrEmpty(fenxiao.getFxname6())){
            Jinfo item = new Jinfo();
            item.setMsg(fenxiao.getFxname6());
            item.setCode(6);
            list.add(item);
        }
        if(!map.containsKey("7")&& !Strings.isNullOrEmpty(fenxiao.getFxname7())){
            Jinfo item = new Jinfo();
            item.setMsg(fenxiao.getFxname7());
            item.setCode(7);
            list.add(item);
        }

        jinfo.setData(list);
        return jinfo;
    }

    @RequestMapping("/admin/fenxiaofan/getTuiLeftLevel")
    @ResponseBody
    public Jinfo getTuiLeftLevel(String hytype) {
        Jinfo jinfo = new Jinfo();
        Long mpid = ObjectUtil.getMpid();
        Fenxiao fenxiao = fenxiaoService.selectOne(new EntityWrapper<Fenxiao>()
                .eq("mpid",mpid).eq("hytype",hytype)
        );
        if(fenxiao==null) return jinfo;

        List<FenxiaoFan> fxflist = fenxiaofanService.selectList(new EntityWrapper<FenxiaoFan>()
                .eq("mpid",mpid).eq("hytype",hytype)
        );
        Map<String,String> map = new HashMap();
        // 不加限制
//        for(FenxiaoFan item:fxflist){
//            map.put(item.getTlevel().toString(),item.getHytype().toString());
//        }
        List<Jinfo> list = new ArrayList<>();
        if(!map.containsKey("1")&& !Strings.isNullOrEmpty(fenxiao.getFxname1())){
            Jinfo item = new Jinfo();
            item.setMsg(fenxiao.getFxname1());
            item.setCode(1);
            list.add(item);
        }
        if(!map.containsKey("2")&& !Strings.isNullOrEmpty(fenxiao.getFxname2())){
            Jinfo item = new Jinfo();
            item.setMsg(fenxiao.getFxname2());
            item.setCode(2);
            list.add(item);
        }
        if(!map.containsKey("3")&& !Strings.isNullOrEmpty(fenxiao.getFxname3())){
            Jinfo item = new Jinfo();
            item.setMsg(fenxiao.getFxname3());
            item.setCode(3);
            list.add(item);
        }
        if(!map.containsKey("4")&& !Strings.isNullOrEmpty(fenxiao.getFxname4())){
            Jinfo item = new Jinfo();
            item.setMsg(fenxiao.getFxname4());
            item.setCode(4);
            list.add(item);
        }
        if(!map.containsKey("5")&& !Strings.isNullOrEmpty(fenxiao.getFxname5())){
            Jinfo item = new Jinfo();
            item.setMsg(fenxiao.getFxname5());
            item.setCode(5);
            list.add(item);
        }
        if(!map.containsKey("6")&& !Strings.isNullOrEmpty(fenxiao.getFxname6())){
            Jinfo item = new Jinfo();
            item.setMsg(fenxiao.getFxname6());
            item.setCode(6);
            list.add(item);
        }
        if(!map.containsKey("7")&& !Strings.isNullOrEmpty(fenxiao.getFxname7())){
            Jinfo item = new Jinfo();
            item.setMsg(fenxiao.getFxname7());
            item.setCode(7);
            list.add(item);
        }

        jinfo.setData(list);
        return jinfo;
    }

    private List<Jinfo> initHytypes(List<Fenxiao> fxlist){
        List<Jinfo> result = new ArrayList<>();
        for(int i=1;i<=5;i++){
            boolean exsist = false ;
            for(Fenxiao fenxiao:fxlist){
                if(fenxiao.getHytype()==i){
                    exsist = true;
                }
            }
            if(exsist){
                if(i==1){
                    Jinfo jinfo = new Jinfo();
                    jinfo.setCode(1);
                    jinfo.setMsg("用户级");
                    result.add(jinfo);
                }
                if(i==2){
                    Jinfo jinfo = new Jinfo();
                    jinfo.setCode(2);
                    jinfo.setMsg("商家级");
                    result.add(jinfo);
                }
                if(i==3){
                    Jinfo jinfo = new Jinfo();
                    jinfo.setCode(3);
                    jinfo.setMsg("代理级");
                    result.add(jinfo);
                }
                if(i==4){
                    Jinfo jinfo = new Jinfo();
                    jinfo.setCode(4);
                    jinfo.setMsg("导购级");
                    result.add(jinfo);
                }
                if(i==5){
                    Jinfo jinfo = new Jinfo();
                    jinfo.setCode(5);
                    jinfo.setMsg("平台级");
                    result.add(jinfo);
                }
            }
        }
        return result;
    }

}
